<?php

namespace app\api\controller\kuerp\pda;

use app\admin\library\traits\Backend;
use app\admin\model\kuerp\Customers;
use app\admin\model\kuerp\Goods;
use app\admin\model\kuerp\GoodsSalesOrder;
use app\admin\model\kuerp\Suppliers;
use app\common\controller\Api;
use think\Config;
use think\Db;
use app\api\library\kuerp\AdminUserAuth as Auth;
use Exception;
use think\Session;

class Sales extends Api
{
    // protected $noNeedLogin = ['login', 'getGoodsInfo', 'getSuppliers', 'getUnit', 'getCodes'];
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $auth_s;
    protected $model = null;
    protected $dataLimit = 'personal'; //表示开启数据权限限制
    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'admin_id';

    protected $excludeFields = null;

    use Backend;

    public function _initialize()
    {
        parent::_initialize();
        $this->auth_s = new Auth();
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        // dump($token);exit;
        $this->auth_s->init($token);
        // dump($this->auth_s->getUser());exit;
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    //获取商品信息
    public function getGoodsInfo()
    {
        $code = $this->request->get('code');
        if (!$code) {
            $this->error(__('error_please_scan_or_input_goods_code'));
        }
        $goods = Db::name('kuerp_goods')->where((['goods_barcode' => $code]))->find();

        if (empty($goods)) {
            // $this->error('product_not_exists');

            $goods_attr = Db::name('kuerp_goods_attr')->where(['barcode'=>$code])->find();
            if(empty($goods_attr)){
                $this->error('not found goods');
            }

            $goods = Db::name('kuerp_goods')->where(['id'=>$goods_attr['goods_id']])->find();

            //如果是属性条码  查询属性辅助集合表
            // $attrIds = Db::name('kuerp_aux_combination')->where(['id'=>$goods_attr['attribute_id']])->value('attr_ids');

            $goods['attribute_id'] = $goods_attr['id'];
        }

        $goods['baseInfo'] = $this->getUnit($goods['goods_code']);

        return $this->success('ok', $goods);
    }

    function checkOutTime($time)
    {
        $checktime = Db::name('kuerp_checkout')->order(['checktime' => 'DESC'])->value('checktime');
        $checkdate = Db::name('kuerp_checkout')->order(['checktime' => 'DESC'])->value('checkdate');
        if (strpos($time, ' - ') !== false) {
            $time = strtotime($time);
        }
        if (strpos($time, '-') !== false) {
            $time = strtotime($time);
        }
        if ($time <= $checktime) {
            $this->error(__('cannot_operate_data_before_checkout_date', $checkdate));
        }
    }

    public function index()
    {

        $userLoginInfo = $this->auth_s->getUser();
        if (empty($userLoginInfo)) {
            $this->error(__('Please login first'), null, 401);
        }

        $where = [];
        $where['goods_sales_order.status'] = ['>=', '0'];

        $sort = 'purchase_time';
        $order = 'DESC';
        $list = GoodsSalesOrder::with(['customers', 'preparation', 'examine','salesUser'])
            ->where($where)
            ->order($sort, $order)
            ->order('purchase_code', 'DESC')
            ->paginate(20);

        foreach ($list as $row) {
            $row->getRelation('customers')->visible(['customer_name']);
            $row->getRelation('preparation')->visible(['username']);
            $row->getRelation('examine')->visible(['username']);
            // $row->getRelation('salesUser')->visible(['name']);
        }
        foreach ($list as $list_k => $list_v) {
            if (isset($list_v['print_num']) && empty($list_v['print_num'])) {
                $list[$list_k]['print_num'] = 0;
            }
            $purchase_id = Db::name('kuerp_goods_saleord')->where(['order_id' => $list_v['id']])->column('purchase_id');
            $purchase = Db::name('kuerp_goods_sales')->where(['id' => ['in', $purchase_id]])->column('purchase_code');
            $list[$list_k]['purchase_id'] = implode(',', $purchase);
        }

        return $this->success('', $list);
    }

    public function add($type = '')
    {

        $this->model = new \app\admin\model\kuerp\GoodsSalesOrder;

        $userLoginInfo = $this->auth_s->getUser();
        // dump($userLoginInfo);exit;

        if (empty($userLoginInfo)) {
            $this->error(__('Please login first'), null, 401);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            // dump($params);exit;
            $examine= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
            if ($params) {
                
                if(empty($params['customers_id'])){
                    $this->error(__('error_please_select_customer'));
                }
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if(!isset($status)){
                    $this->error(__('please_fill_detail_data'));
                }
                $params = $this->preExcludeFields($params);
                $admin = Session::get('admin');

                if(empty($params['purchase_code'])){
                    $this->error(__('please_fill_document_number'));
                }

                if(empty($params['customers_id'])){
                    $this->error(__('error_please_select_customer'));
                }
                $customers = Db::name('kuerp_customers')->where(['id'=>$params['customers_id']])->find();
                if(empty($customers)){
                    $this->error(__('customer_not_exists'));
                }

                $data = [];
                $number = 0;$all_money = 0;$tax_money=0;$money_tax_price=0;
                // dump($params);exit;
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number+=$params['number'][$k];
                        $all_money = bcadd($params['all_money'][$k],$all_money,2);
                        $tax_money += (float)$params['all_money'][$k];
                        $money_tax_price += (float)$params['all_money'][$k];
                       

                        $goods = Db::name('kuerp_goods')->where(['goods_code'=>$v])->find();
                        if(empty($goods)){
                            $this->error(__('goods_not_exists'));
                        }elseif ($goods['auxiliary']==1 && empty($params['goods_attr'][$k])){
                            $this->error(__('error_please_select_goods_attribute'));
                        }

                        $data[] = [
                            'purchase_code'     =>  $params['purchase_code'],
                            'purchase_type'     =>  $params['purchase_type'],
                            'purchase_time'     =>  strtotime($params['purchase_time']),
                            'delivery_time'     =>  strtotime($params['delivery_time']),
                            'customers_id'      =>  (int)$params['customers_id'],//客户
                            'sale_user'         =>  (int)$params['sale_user'],//销售员
                            'receiving_address' =>  $params['receiving_address'] ?? null,

                            'goods_code'        =>  $v,//商品信息
                            'goods_note'        =>  $params['goods_note'][$k],
                            'goods_unit'        =>  (int)$params['goods_unit'][$k],

                            'stores_id'         =>  (int)$params['stores_id'][$k],
                            'allow_stock'       =>  (float)$params['allow_stock'][$k],
                            'number'            =>  (float)$params['number'][$k],
                            'purchase_number'   =>  (float)$params['number'][$k],
                            'default_unit'      =>  (float)$params['goods_unit'][$k],
                            'basic_nmber'       =>  (float)$params['basic_number'][$k],
                            'unit_price'        =>  (float)$params['unit_price'][$k],
                            'cost_price'        =>  (new Goods())->getCost_Price($v,$params['stores_id'][$k]),
                            // 'discount'          =>  (float)$params['discount'][$k],
                            // 'dis_money'         =>  (float)$params['dis_money'][$k],
                            'all_money'         =>  (float)$params['all_money'][$k],
                            // 'remark'            =>  $params['remark'][$k],

                            // 'preferential_rate' =>  (float)$params['preferential_rate'],
                            // 'preferential_money'=>  (float)$params['preferential_money'],
                            'real_money'        =>  (float)$params['all_money'][$k],

                            'goods_attr'        =>  (float)$params['goods_attr'][$k],
                            // 'tax_included'      =>  (float)$params['tax_included'][$k],
                            // 'tax_rate'          =>  (float)$params['tax_rate'][$k],
                            'tax_money'         =>  (float)$params['all_money'][$k],
                            'money_tax_price'   =>  (float)$params['all_money'][$k],

                            'preparation_id'    =>  $userLoginInfo['id'],
                            'operation_id'      =>  $userLoginInfo['id'],

                            'library_number'    =>  (float)$params['number'][$k],
                            'library_money'     =>  (float)$params['all_money'][$k],

                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }
                }
                // dump($data);
                if(!empty($data)){
                    $row = [
                        'purchase_code'     =>  $params['purchase_code'],
                        'purchase_type'     =>  $params['purchase_type'],
                        'purchase_time'     =>  strtotime($params['purchase_time']),
                        'delivery_time'     =>  strtotime($params['delivery_time']),
                        'customers_id'      =>  (int)$params['customers_id'],//客户
                        'sale_user'         =>  (int)$params['sale_user'],//销售员
                        'receiving_address' =>  $params['receiving_address'] ?? null,
                        'number'            =>  $number,
                        'all_money'         =>  $all_money,

                        'tax_money'         =>  $tax_money,
                        'money_tax_price'   =>  $all_money,

                        // 'preferential_rate' =>  (float)$params['preferential_rate'],
                        // 'preferential_money'=>  (float)$params['preferential_money'],
                        'real_money'        => $all_money,
                        // 'note'              =>  $params['note'],
                        'preparation_id'    =>   $userLoginInfo['id'],
                        'operation_id'      =>   $userLoginInfo['id'],
                        'createtime'        => time(),
                        'updatetime'        => time(),
                    ];
                }

                // dump($data);exit;
                if($this->model->where(['purchase_code'=>trim($params['purchase_code'])])->find()){
                    $this->error(__('document_number_already_used'));
                }

                //附件记录开始
                $enclosureLog = [];
                if(isset($params['enclosure']) && !empty($params['enclosure'])){//选择了原始单据
                    $enclosure = explode(',',$params['enclosure']);
                    $enclosurelist = Db::name('kuerp_enclosure')->where(['id'=>['in',$params['enclosure']]])->select();
                    if(sizeof($enclosurelist)!=sizeof($enclosure)){
                        $this->error(__('selected_original_document_error_please_reselect'));
                    }else{
                        foreach ($enclosure as $k=>$v){
                            $enclosureLog[] = [
                                'enclosure_id'  => $v,
                                'purchase_code' => $params['purchase_code'],
                                'type'          => '4',
                            ];
                        }
                    }
                    unset($params['enclosure']);
                }
                //附件记录结束

                $result = false;
                Db::startTrans();
                try {
                    if(!empty($row)){
                        $result = $this->model->insertGetId($row);
                    }

                    //添加附件记录
                    if(!empty($enclosureLog)){
                        foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                            $enclosureLog[$enclosureLog_k]['order_id'] = $result;
                        }
                        Db::name('kuerp_enclosure_log')->insertAll($enclosureLog);
                    }
                    //添加附件记录结束

                    Db::name('kuerp_goods_sales_order_info')->where(['purchase_code'=>$params['purchase_code']])->delete();
                    Db::name('kuerp_goods_sales_order_info')->insertAll($data);
                    Db::commit();
                    return json(['result' => $result, 'msg' => 'ok', 'code' => 200]);
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            // $this->error(__('Parameter %s can not be empty', ''));
        } 
    }

    public function detail(){

        $purchaseCode = $this->request->get('purchase_code');

        $purchase_info = GoodsSalesOrder::with(['goodsSalesOrderInfo','goodsSalesOrderInfo.goodsAttrInfo,unit,store,goods,customers,saleUser'])->where(['purchase_code'=>$purchaseCode])->find();

         foreach($purchase_info['goods_sales_order_info'] as $row) {

            $attr_set_id = $row['goods_attr_info']['attribute_id'];

            //查询辅助属性集合
            $aux_combination_ids = Db::name('kuerp_aux_combination')->where('id', $attr_set_id)->value('attr_ids');

            $ids = explode('&', $aux_combination_ids);

            //查询最终的attr_name
            $attr_names = Db::name('kuerp_auxiliary')->whereIn('id', $ids)->column('name');

            $row['goods_attr_info']['attr_name'] = implode('/', $attr_names);
        }
        
        return $this->success('ok', $purchase_info);
        
    }

    public function del($ids = "")
    {

        $userLoginInfo = $this->auth_s->getUser();
        if (empty($userLoginInfo)) {
            $this->error(__('Please login first'), null, 401);
        }

        $this->model = new \app\admin\model\kuerp\GoodsSalesOrder();

        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = 'id';
            $adminIds = $this->getDataLimitAdminIds();
         
            $examine= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');

            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            // dump($list);

            foreach ($list as $list_k=>$list_v){

                if($list_v['purchase_type']==1){
                    $purchase_id = Db::name('kuerp_goods_saleord')->where(['order_id'=>$list_v['id']])->column('purchase_id');
                    if(!empty($purchase_id)){
                        $this->error(__('cannot_delete_generated_sales_data'));
                    }
                }else{
                    $purchase_id = Db::name('kuerp_goods_saleexc')->where(['purchase_id'=>$list_v['id'],'type'=>'1'])->column('exchange_id');
                    if(!empty($purchase_id)){
                        $this->error(__('cannot_delete_generated_return_data'));
                    }
                }
            }

            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    $this->error(__('cannot_delete_approved_data'));
                }elseif ($list_v['examine_status']==1 && $examine!=1){
                   
                }
            }

            // dump($list);exit;

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    Db::name('kuerp_goods_sales_order_info')->where(['purchase_code'=>$v['purchase_code']])->delete();

                    //删除附件记录
                    Db::name('kuerp_enclosure_log')->where(['purchase_code'=>$v['purchase_code'],'type'=>'4'])->delete();
                }
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
        if (!$this->dataLimit) {
            return null;
        }

        // dump($this->auth_s->getUser

        if ($this->auth_s->isSuperAdmin()) {
            return null;
        }
        $adminIds = [];
        if (in_array($this->dataLimit, ['auth', 'personal'])) {
            $adminIds = $this->dataLimit == 'auth' ? $this->auth_s->getChildrenAdminIds(true) : [$this->auth_s->getUser()['id']];
        }
        return $adminIds;
    }

    public function customers()
    {
        $data = input();
        $wheres = [];
        if (isset($data['keywords'])) {
            $wheres['customers.status'] = '1';
        }
        $list = Customers::with(['customertype', 'customerlevel', 'saler'])
            ->where($wheres)
            ->select();

        foreach ($list as $row) {
            $row->getRelation('customerlevel')->visible(['name']);
            $row->getRelation('customertype')->visible(['type_name']);
            $row->getRelation('saler')->visible(['name']);
        }

        return $this->success('success', $list);
    }

    public function getSalesPerson()
    {
        $data = input();
        $wheres = [];
        if (isset($data['keywords'])) {
            $wheres['name'] = ['like', "%{$data['keywords']}%"];
            $wheres['status'] = '1';
        } else {
            $wheres['status'] = '1';
        }
        $list = Db::name('kuerp_staff_member')->where($wheres)->field('id,name')->select();

        return $this->success('success', $list);
    }

    //获取单位价格信息
    public function getUnit($goods_code = '', $store = '', $attr = '', $supplyer_code = '')
    {
        $set = Db::name('kuerp_sets')->where(['name' => 'taxes'])->field('value,is_checked')->find();
        $taxes = Db::name('kuerp_sets')->where(['name' => 'price_taxes'])->value('is_checked');

        if ($goods_code) {
            $row = Db::name('kuerp_goods')->where(['goods_code' => $goods_code])->field('batch,serial,id,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')->find();
            $goods_id = isset($row['id']) ? $row['id'] : 0;
        } else {
            $goods_id = isset($_POST['goods_id']) ? $_POST['goods_id'] : 0;
            $row = Db::name('kuerp_goods')->where(['id' => $goods_id])->field('batch,serial,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')->find();
        }
        if (empty($row)) {
            return [];
        }
        if ($supplyer_code) {
            $suppliers = Db::name('kuerp_suppliers')->where(['supplyer_code' => $supplyer_code])->value('vat_rate');
        }

        $auxiliary = Db::name('kuerp_auxiliary')->where(['status' => 1])->column('name', 'id');
        $goods_attr = Db::name('kuerp_goods_attr')->where(['goods_id' => $goods_id])->select();
        foreach ($goods_attr as $goods_attr_k => $goods_attr_v) {
            $aux_combination = Db::name('kuerp_aux_combination')->where(['id' => $goods_attr_v['attribute_id']])->value('attr_ids');
            $goods_attr[$goods_attr_k]['attr_ids'] = [];
            $goods_attr[$goods_attr_k]['attr_name'] = '';
            if ($aux_combination) {
                $goods_attr[$goods_attr_k]['attr_id'] = $aux_combination;
                $aux_combination = explode('&', $aux_combination);
                $goods_attr[$goods_attr_k]['attr_ids'] = $aux_combination;
                foreach ($aux_combination as $aux_combination_k => $aux_combination_v) {
                    $aux_combination[$aux_combination_k] = isset($auxiliary[$aux_combination_v]) ? $auxiliary[$aux_combination_v] : '';
                }
                $aux_combination = implode('/', $aux_combination);
                $goods_attr[$goods_attr_k]['attr_name'] = $aux_combination;
            }
        }


        $where = [];
        $where['goods_id'] = $goods_id;
        if ($store) {
            $where['stores_id'] = $store;
        } else {
            $where['stores_id'] = $row['manager_warehouse_id'];
        }
        if ($attr) {
            //$attribute_id = Db::name('kuerp_goods_attr')->where(['goods_id'=>$goods_id,'id'=>$attr])->value('attribute_id');
            $where['attribute_id'] = $attr;
        }
        $stock = Db::name('kuerp_goods_stock')->where($where)->value('stock');
        if ($row['more_unit'] == 1) {
            $unit = Db::name('kuerp_unit_conversion')->alias('uc')
                ->join('kuerp_unit u', 'u.id=uc.vice_unit')
                ->where(['uc.main_unit' => $row['unit_id']])
                ->order('uc.advance_rate', 'ASC')
                ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                ->select();
            $unit_ids = [$row['unit_id']];
            foreach ($unit as $unit_k => $unit_v) {
                $unit_ids[] = $unit_v['id'];
            }
            $goods_price = Db::name('kuerp_goods_price')->where(['unit' => ['in', $unit_ids], 'goods_id' => $goods_id])->select();
            foreach ($goods_price as $goods_price_k => $goods_price_v) {
                foreach ($unit as $unit_k => $unit_v) {
                    if ($goods_price_v['unit'] == $row['unit_id']) {
                        $goods_price[$goods_price_k]['advance_rate'] = 1;
                    } else if ($goods_price_v['unit'] == $unit_v['id']) {
                        $goods_price[$goods_price_k]['advance_rate'] = $unit_v['advance_rate'];
                    }
                }
            }
        } else {
            $unit_ids = [$row['unit_id']];
        }
        $unit = Db::name('kuerp_unit')->where(['id' => ['in', $unit_ids]])->field('id,name')->select();
        foreach ($unit as $unit_k => $unit_v) {
            if (isset($goods_price)) {
                foreach ($goods_price as $goods_price_k => $goods_price_v) {
                    if ($unit_v['id'] == $goods_price_v['unit']) {
                        $unit[$unit_k]['is_default'] = $goods_price_v['is_default'];
                        //$unit[$unit_k]['purchase'] = $goods_price_v['purchase']*$goods_price_v['advance_rate'];
                        $unit[$unit_k]['purchase'] = $goods_price_v['purchase'];
                        if ($goods_price_v['is_default'] != 1) {
                            $unit[$unit_k]['basic_nmber'] = $goods_price_v['advance_rate'];
                        } else {
                            $unit[$unit_k]['basic_nmber'] = 1;
                        }
                    }
                }
            } else {
                if ($row['auxiliary'] == 1 && !empty($attr)) {
                    $purchase = Db::name('kuerp_goods_attr')->where(['goods_id' => $goods_id, 'id' => $attr])->value('purchase');
                } else {
                    $purchase = $row['purchase'];
                }
                if ($unit_v['id'] == $row['unit_id']) {
                    $unit[$unit_k]['is_default'] = 1;
                    $unit[$unit_k]['basic_nmber'] = 1;
                    $unit[$unit_k]['purchase'] = $purchase;
                }
            }
        }
        foreach ($unit as $unit_k => $unit_v) {
            if (isset($suppliers) && $suppliers !== '') {
                $tax = $suppliers;
            } else {
                $tax = $set['value'];
            }
            if (isset($set['is_checked']) && isset($set['value']) && $set['is_checked'] == 1) {
                $unit[$unit_k]['tax'] = 1;
                $unit[$unit_k]['tax_rate'] = $tax;
            } else {
                $unit[$unit_k]['tax'] = 0;
                $unit[$unit_k]['tax_rate'] = 0;
            }
            if (isset($set['is_checked']) && isset($set['value']) && $set['is_checked'] == 1 && $taxes == 1) {
                $unit[$unit_k]['purchase'] = round(($unit_v['purchase'] / (100 + $tax) * 100), 4);
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            } elseif (isset($set['is_checked']) && isset($set['value']) && $set['is_checked'] == 1 && $taxes != 1) {
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = round(($unit_v['purchase'] * (100 + $tax) / 100), 4);
            } else {
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            }
        }
        $data = [];
        foreach ($unit_ids as $unit_ids_k => $unit_ids_v) {
            foreach ($unit as $unit_k => $unit_v) {
                if ($unit_ids_v == $unit_v['id']) {
                    if ($unit_v['is_default'] == 1) {
                        $unit_v['stock'] = is_null($stock) ? 0 : $stock;
                    } else {
                        $unit_v['stock'] = round($stock / $unit_v['basic_nmber'], 2);
                    }
                    $unit_v['tax_money'] = round(($unit_v['tax_included'] - $unit_v['purchase']), 4);;
                    $data[] = $unit_v;
                }
            }
        }
        return ['unit' => $data, 'attr' => $goods_attr, 'goods' => $row];
    }

    public function getCodes($code = '', $type, $new = true)
    {
        $set = \think\Db::name('kuerp_prefix')->where(['type' => $type])->find();
        if (empty($set)) {
            return '';
        } else {
            if (!empty($set['dbname']) && !empty($set['field']) && empty($code) && $new && $type < 7) {
                $code = \think\Db::name($set['dbname'])->order([$set['field'] => 'DESC'])->value($set['field']);
            }
            preg_match_all("/\d+/", $code, $num);
            $order_num = implode('', $num[0]);
            if ($code && $new) {
                try {
                    if ($set['year'] == 1) {
                        $order_num = substr($order_num, 4);
                    }
                    if ($set['month'] == 1) {
                        $order_num = substr($order_num, 2);
                    }
                    if ($set['day'] == 1) {
                        $order_num = substr($order_num, 2);
                    }
                    if ($set['hour'] == 1) {
                        $order_num = substr($order_num, 2);
                    }
                    if ($set['minute'] == 1) {
                        $order_num = substr($order_num, 2);
                    }
                    if ($set['second'] == 1) {
                        $order_num = substr($order_num, 2);
                    }
                } catch (\Exception $e) {
                }
            }
            if ($order_num < $set['start']) {
                $order_num = $set['start'];
            } else {
                $order_num = (float)$order_num + 1;
            }
            $prefix = $set['prefix'];
            if ($set['year'] == 1) {
                $prefix = $prefix . date('Y');
            }
            if ($set['month'] == 1) {
                $prefix = $prefix . date('m');
            }
            if ($set['day'] == 1) {
                $prefix = $prefix . date('d');
            }
            if ($set['hour'] == 1) {
                $prefix = $prefix . date('H');
            }
            if ($set['minute'] == 1) {
                $prefix = $prefix . date('i');
            }
            if ($set['second'] == 1) {
                $prefix = $prefix . date('s');
            }
            $s = '';
            if (strlen($order_num) < $set['strlen']) {
                for ($a = 1; $a <= $set['strlen'] - (strlen($order_num)); $a++) {
                    $s .= '0';
                }
            }
            $code = $order_num;
            $order_num = $prefix . $s . $order_num;
        }
        if (!empty($set['dbname']) && !empty($set['field'])) {
            $res = \think\Db::name($set['dbname'])->where([$set['field'] => $order_num])->value('id');
            if ($res) {
                return $this->getCodes($code, $type, false);
            }
        }
        return $order_num;
    }
}
